package cn.net.shuxing.yifu.common.front.controller;

import cn.net.shuxing.yifu.common.bean.*;
import cn.net.shuxing.yifu.common.constant.UserType;
import cn.net.shuxing.yifu.common.dto.BaseDto;
import cn.net.shuxing.yifu.common.dto.CodeConst;
import cn.net.shuxing.yifu.common.service.*;
import cn.net.shuxing.yifu.common.util.FileUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/front/my")
public class MyInfoController extends BaseController {

    @Autowired
    private UserRealInfoService userRealInfoService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserCommonService userCommonService;

    @Autowired
    private ShareholderCommonService shareholderCommonService;

    @Autowired
    private UserTransferService userTransferService;

    @Autowired
    private DealHistoryService dealHistoryService;

    @Autowired
    private HangBuyService hangBuyService;

    @Autowired
    private HangSaleService hangSaleService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private CoinTypeService coinTypeService;

    @Autowired
    private UserWithdrawalCashService userWithdrawalCashService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RechargeHistoryService rechargeHistoryService;

    @Autowired
    private MyWalletController myWalletController;

    @Autowired
    private UserDealHistoryService userDealHistoryService;

    /**
     * 获取用户所有身份
     *
     * @param userId
     * @return
     */
    @RequestMapping("/role/all")
    public BaseDto getAllRole(Integer userId) {
        BaseDto baseDto = checkUserId(userId);
        if (baseDto != null && baseDto.isError())
            return baseDto;
        return BaseDto.ok(userRoleService.getsByUserId(userId));
    }

    /**
     * 基础信息
     *
     * @param userId
     * @return
     */
    @RequestMapping("/info/base")
    public BaseDto getAllRoleDetail(Integer userId) {
        BaseDto baseDto = checkUserId(userId);
        if (baseDto != null && baseDto.isError())
            return baseDto;
        User user = userService.getByPrimaryKeyWithoutComplete(userId);
        BaseDto capitalToCNY = myWalletController.getCapitalToCNY(userId, user.getType());
        BigDecimal totalToCNY = new BigDecimal(0);
        if (capitalToCNY != null && !capitalToCNY.isError())
            totalToCNY = ((Map<String, BigDecimal>) capitalToCNY.getData()).get("totalCount");
        List<UserDealHistory> userDealHistoryList = userDealHistoryService.getHistoryByUserIdAndDay(userId, 30);
        BigDecimal newestDealtCount = new BigDecimal(0);
        if (userDealHistoryList != null) {
            for (UserDealHistory userDealHistory : userDealHistoryList) {
                newestDealtCount = newestDealtCount.add(userDealHistory.getDealAliveCoinCount());
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId", user.getId());
        map.put("username", user.getUsername());
        map.put("totalToCNY", totalToCNY);
        map.put("dealtCount", newestDealtCount);

        return BaseDto.ok(map);

        /*
        {
            userId: 用户id,
            username: 用户名,
            totalToCNY: 总资产折合,
            dealtCount: 近30天交易量
        }
         */
    }


    @ApiOperation("获取个人完整信息")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Integer", paramType = "query")
    @RequestMapping("/info")
    public BaseDto getMyInfo(Integer userId) {
        BaseDto baseDto = checkUserId(userId);

        if (baseDto != null && baseDto.getCode() == CodeConst.ERROR)
            return baseDto;
        baseDto = new BaseDto();
//        if (isStateNone(userId))
//        {
//            User user = userService.getByPrimaryKey(userId);
//            UserCompletedInfo userCompletedInfo = new UserCompletedInfo();
//            userCompletedInfo.setUser(user);
//            baseDto.setData(userCompletedInfo);
//            return baseDto;
//        }
//        else
//        {
        User user = userService.getByPrimaryKey(userId);
        if (user.getType() == UserType.MEMBER || user.getType() == UserType.NONE) {
            UserCompletedInfo userCompletedInfo = userCommonService.searchByUserId(userId);
            baseDto.setData(userCompletedInfo);
            return baseDto;
        }
        if (user.getType() == UserType.SHAREHOLDER) {
            ShareholderCompletedInfo shareholderCompletedInfo = shareholderCommonService.searchByUserId(userId);
            baseDto.setData(shareholderCompletedInfo);
            return baseDto;
        } else {
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("当前身份暂不支持");
            return baseDto;
        }
//        }
    }

    @ApiOperation(value = "获取所有转账记录", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "分页显示的页数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页显示本页显示数据的条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping("/transfer/all")
    public BaseDto getTotalUserTransferList(Integer userId,
                                            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Page page = PageHelper.startPage(pageNum, pageSize);
        PageInfo<UserTransfer> userTransferPageInfo = new PageInfo<>(userTransferService.getTotalByUserId(userId));
        BaseDto baseDto = new BaseDto();
        baseDto.setData(userTransferPageInfo.getList());
        return baseDto;
    }

    @ApiOperation(value = "获取本月转账记录", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "分页显示的页数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页显示本页显示数据的条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping("/transfer/thisMonth")
    public BaseDto getThisMonthUserTransferList(Integer userId,
                                                @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Page page = PageHelper.startPage(pageNum, pageSize);
        PageInfo<UserTransfer> userTransferPageInfo = new PageInfo<>(userTransferService.getThisMonthByUserId(userId));
        BaseDto baseDto = new BaseDto();
        baseDto.setData(userTransferPageInfo.getList());
        return baseDto;
    }

    @ApiOperation(value = "获取我的所有挂买单信息", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "分页显示的页数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页显示本页显示数据的条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping("/hangBuy/all")
    public BaseDto getHangBuyListByUserId(Integer userId,
                                          @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        List<HangBuy> HangBuyList = hangBuyService.getTotalByUserId(userId, pageNum, pageSize);
        BaseDto baseDto = new BaseDto();
        baseDto.setData(HangBuyList);
        return baseDto;
    }

    @ApiOperation(value = "获取我的所有挂卖单信息", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "分页显示的页数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页显示本页显示数据的条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping("/hangSale/all")
    public BaseDto getHangSaleListByUserId(Integer userId,
                                           @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        List<HangSale> hangSaleList = hangSaleService.getTotalByUserId(userId, pageNum, pageSize);
        BaseDto baseDto = new BaseDto();
        baseDto.setData(hangSaleList);
        return baseDto;
    }

    @ApiOperation(value = "获取挂买单详情", httpMethod = "GET")
    @ApiImplicitParam(name = "hangBuyId", value = "挂买单id", required = true, dataType = "Integer", paramType = "query")
    @RequestMapping("/hangBuy/id")
    public BaseDto getHangBuyById(Integer hangBuyId) {
        HangBuy hangBuy = hangBuyService.getByPrimaryKey(hangBuyId);
        HangBuyList hangBuyList = new HangBuyList();
        Integer userId = hangBuy.getUserId();
        UserCompletedInfo userCompletedInfo = userCommonService.searchByUserId(userId);
        hangBuyList.setHangBuyId(hangBuyId);
        //挂买人
        String hangBuyUser = userCompletedInfo.getUserRealInfo().getRealName();
        hangBuyList.setHangBuyUser(hangBuyUser);
        //手机号
        String phoneNum = userCompletedInfo.getUserInfoBind().getPhoneNum();
        hangBuyList.setPhoneNum(phoneNum);
        //币种
        String coinType = coinTypeService.getByPrimaryKey(hangBuy.getCoinTypeId()).getName();
        hangBuyList.setCoinType(coinType);
        //挂买数量
        BigDecimal hangBuyNum = hangBuy.getAliveCoinCount();
        hangBuyList.setHangBuyNum(hangBuyNum);
        //挂买单价
        BigDecimal hangBuyPrice = hangBuy.getSinglePrice();
        hangBuyList.setHangBuyPrice(hangBuyPrice);
        //已交易数量
        BigDecimal surplusCoinCount = hangBuy.getSurplusCoinCount();//余量
        BigDecimal hangBuyDealNum = hangBuyNum.subtract(surplusCoinCount);
        hangBuyList.setHangBuyDealNum(hangBuyDealNum);
        //挂买单状态
        Integer stateNum = hangBuy.getState();
        String hangBuyState = "";
        if (stateNum == 0) {
            hangBuyState = "已完成";
        } else if (stateNum == 1) {
            hangBuyState = "撤单";
        } else if (stateNum == 2) {
            hangBuyState = "交易中";
        } else {
            hangBuyState = "订单异常";
        }
        hangBuyList.setHangBuyState(hangBuyState);
        //发布时间
        LocalDateTime publistTime = hangBuy.getCreateTime();
        hangBuyList.setPublistTime(publistTime);

        BaseDto baseDto = new BaseDto();
        baseDto.setData(hangBuyList);
        return baseDto;
    }

    @ApiOperation(value = "获取挂卖单详情", httpMethod = "GET")
    @ApiImplicitParam(name = "hangSaleId", value = "挂卖单id", required = true, dataType = "Integer", paramType = "query")
    @RequestMapping("/hangSale/id")
    public BaseDto getHangSaleByIc(Integer hangSaleId) {
        HangSale hangSale = hangSaleService.getByPrimaryKey(hangSaleId);
        HangSaleList hangSaleList = new HangSaleList();
        Integer userId = hangSale.getUserId();
        UserCompletedInfo userCompletedInfo = userCommonService.searchByUserId(userId);
        hangSaleList.setHangSaleId(hangSaleId);
        //挂买人
        String hangSaleUser = userCompletedInfo.getUserRealInfo().getRealName();
        hangSaleList.setHangSaleUser(hangSaleUser);
        //手机号
        String phoneNum1 = userCompletedInfo.getUserInfoBind().getPhoneNum();
        hangSaleList.setPhoneNum(phoneNum1);
        //币种
        String coinType = coinTypeService.getByPrimaryKey(hangSale.getCoinTypeId()).getName();
        hangSaleList.setCoinType(coinType);
        //挂买数量
        BigDecimal hangSaleNum = hangSale.getAliveCoinCount();
        hangSaleList.setHangSaleNum(hangSaleNum);
        //挂买单价
        BigDecimal hangSalePrice = hangSale.getSinglePrice();
        hangSaleList.setHangSalePrice(hangSalePrice);
        //已交易数量
        BigDecimal surplusCoinCount = hangSale.getSurplusCoinCount();//余量
        BigDecimal hangSaleDealNum = hangSaleNum.subtract(surplusCoinCount);
        hangSaleList.setHangSaleDealNum(hangSaleDealNum);
        //挂买单状态
        Integer stateNum = hangSale.getState();
        String hangSaleState = "";
        if (stateNum == 0) {
            hangSaleState = "已完成";
        } else if (stateNum == 1) {
            hangSaleState = "撤单";
        } else if (stateNum == 2) {
            hangSaleState = "交易中";
        } else {
            hangSaleState = "订单异常";
        }
        hangSaleList.setHangSaleState(hangSaleState);
        //发布时间
        LocalDateTime publistTime = hangSale.getCreateTime();
        hangSaleList.setPublistTime(publistTime);
        BaseDto baseDto = new BaseDto();
        baseDto.setData(hangSaleList);
        return baseDto;
    }

    @ApiOperation(value = "获取所有提现信息", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "分页显示的页数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页显示本页显示数据的条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping("/withdidraw/info/all")
    public BaseDto getUserWitdrawCashList(Integer userId,
                                          @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Page page = PageHelper.startPage(pageNum, pageSize);
        PageInfo<UserWithdrawalCash> userWithdrawalCashPageInfo = new PageInfo<>(userWithdrawalCashService.getsByUserId(userId));
        BaseDto baseDto = new BaseDto();
        baseDto.setData(userWithdrawalCashPageInfo.getList());
        return baseDto;
    }

    @ApiOperation(value = "获取所有充值信息", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "分页显示的页数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页显示本页显示数据的条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping("/recharge/info/all")
    public BaseDto getRechargeHistoryList(Integer userId,
                                          @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Page page = PageHelper.startPage(pageNum, pageSize);
        PageInfo<RechargeHistory> rechargeHistoryPageInfo = new PageInfo<>(rechargeHistoryService.getsAllCompletedByUserId(userId));
        BaseDto baseDto = new BaseDto();
        baseDto.setData(rechargeHistoryPageInfo.getList());
        return baseDto;
    }

    /**
     * 切换身份
     *
     * @param userId 用户id
     * @param role   身份编号, 0表示无身份，1表示会员，2表示股东，3表示商家
     * @return
     */
    @RequestMapping("/role/change")
    public BaseDto changeUserRole(Integer userId, Integer role) {
        boolean flag = userRealInfoService.checkAbleChange(userId);
        if (!flag) {
            return BaseDto.error("请先实名认证");
        }
        if (role == UserType.MEMBER) {
            boolean b = userService.changeRole(userId, role);
            if (!b) {
                b = userService.changeRole(userId, UserType.NONE);
                if (b) {
                    return BaseDto.ok(userService.getByPrimaryKey(userId));
                }
            }
        }
        if (userService.changeRole(userId, role)) {
            return BaseDto.ok(userService.getByPrimaryKey(userId));
        }
        return BaseDto.error("用户无此身份");
    }

    /** 新增 **/
    /**
     * 上传头像
     *
     * @param userId      用户id
     * @param pictureFile 头像文件
     * @return
     * @throws IOException
     */
    @RequestMapping("/info/picture/upload")
    public BaseDto uploadPicture(Integer userId, @RequestParam("pictureFile") MultipartFile pictureFile) throws IOException {
        String fileName = pictureFile.getOriginalFilename();
        String suffix = FileUtil.getFileExtName(fileName);
        InputStream inputStream = pictureFile.getInputStream();
        byte[] pictureFileContent = new byte[(int) pictureFile.getSize()];
        inputStream.read(pictureFileContent);
        boolean flag = userInfoService.uploadPicture(userId, pictureFileContent, suffix);
        if (flag)
            return BaseDto.ok("上传成功");
        return BaseDto.error("上传失败");
    }
}
